﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public delegate void EditAction(bool isEditMode, bool canSave);

    [ExecuteInEditMode]
    public class MainController : MonoBehaviour
    {
        public int fps = 30;
        public bool useTexturePool = true;
        public bool hideMouse = true;
        public bool backKeyQuit = true;

        //图片永久缓存，直到应用关闭
        private static Dictionary<string, Texture2D> texturePool = new Dictionary<string, Texture2D>();

        public static MainController instance;
        public static bool isEditMode { get; set; }
        public static event EditAction onEditModeEnable;
        public static Action<bool> onFullScreen;
        static string _resPath;

#if !UNITY_ANDROID
        [DllImport("user32.dll")]
        static extern IntPtr SetWindowLong(IntPtr hwnd, int _nIndex, int dwNewLong);
        [DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
        [DllImport("user32.dll")]
        static extern IntPtr GetActiveWindow();
#endif
        const uint SWP_SHOWWINDOW = 0x0040;
        const int GWL_STYLE = -16;
        const int WS_BORDER = 1;
        const int HWndInsertAfter = 0; //层级取0就好，否则打开的FileDialog无法悬浮在其之上

        Rect fullScreenRect;
        int frame = 0;
        const int windowW = 1500, windowH = 468;
        static bool isFullScreen;

        public static string resPath
        {
            get
            {
                if (string.IsNullOrEmpty(_resPath))
                {
#if UNITY_ANDROID
                    _dataPath = Application.persistentDataPath + "/Res";
#else
                    _resPath = Application.dataPath.Replace("/Assets", "") + "/Res";
#endif
                }
                return _resPath;
            }
        }

        void Awake()
        {
            Application.runInBackground = true;
            instance = this;

            Application.targetFrameRate = fps;

            Cursor.visible = Application.isEditor ? true : !hideMouse;

            if (Config.Instance.UseConfigScreenSize)
            {
                Vector2 screenSize = new Vector2(Config.Instance.ScreenW, Config.Instance.ScreenH);
                GetComponent<CanvasScaler>().referenceResolution = screenSize;

                if (Display.displays.Length > 1 && Config.Instance.SelectScreen > 1)
                {
                    fullScreenRect = new Rect(Display.displays[0].systemWidth, 0, Config.Instance.ScreenW, Config.Instance.ScreenH);
                }
                else
                {
                    fullScreenRect = new Rect(0, 0, Config.Instance.ScreenW, Config.Instance.ScreenH);
                }
            }
            else
            {
                if (Display.displays.Length > 1 && Config.Instance.SelectScreen > 1)
                {
                    fullScreenRect = new Rect(Display.displays[0].systemWidth, 0, Display.displays[1].systemWidth, Display.displays[1].systemHeight);
                }
                else
                {
                    fullScreenRect = new Rect(0, 0, Display.displays[0].systemWidth, Display.displays[0].systemHeight);
                }
            }

#if !UNITY_ANDROID
            if (!Directory.Exists(resPath))
            {
                DialogTip.Show("缺少Res文件夹");
            }
#endif
        }

        void Start()
        {
            if (!Directory.Exists(resPath))
            {
                DialogAlert.Show("提示", "Res目录不存在!");
            }

#if UNITY_EDITOR
            //初始化设置为窗口模式，才能使用SetWindowPos()方法设置全屏
            UnityEditor.PlayerSettings.fullScreenMode = FullScreenMode.Windowed;
            UnityEditor.PlayerSettings.resizableWindow = false;
#endif
        }

        void Update()
        {
            if (Input.GetKeyDown(KeyCode.F1))
            {
                isEditMode = !isEditMode;
                if (onEditModeEnable != null)
                {
                    onEditModeEnable(isEditMode, false);
                }
            }
            if (isEditMode && Input.GetKeyDown(KeyCode.Return))
            {
                isEditMode = false;
                if (onEditModeEnable != null)
                {
                    onEditModeEnable(isEditMode, true);
                }
            }
            if (!Application.isEditor && Input.GetKeyDown(KeyCode.F2))
            {
                FullScrenn(!isFullScreen);
                onFullScreen?.Invoke(isFullScreen);
            }
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                if (isEditMode)
                {
                    isEditMode = false;
                    if (onEditModeEnable != null)
                    {
                        onEditModeEnable(isEditMode, false);
                    }
                }
                else
                {
                    Application.Quit();
                }
            }

            if (Input.GetKey(KeyCode.LeftShift) && Input.GetKeyDown(KeyCode.Space))
            {
                Cursor.visible = !Cursor.visible;
            }

            if (!Application.isEditor)
            {
                if (frame < 5)
                {
                    frame++;
                    FullScrenn(true);
                    if (frame == 5)
                    {
                        onFullScreen?.Invoke(true);
                    }
                }
            }
        }

        public static DirectoryInfo[] GetFolders(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            return root.GetDirectories();
        }

        public static FileInfo[] GetFiles(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            return root.GetFiles();
        }

        /// <summary>
        /// 模糊字用*号代替
        /// </summary>
        /// <returns></returns>
        public static string[] SearchFile(string path, string searchPattern, SearchOption searchOption = SearchOption.AllDirectories)
        {
            return Directory.GetFiles(path, searchPattern, searchOption);
        }

        /// <summary>
        /// 从缓存里找图片，没有则直接加载并放入缓存
        /// </summary>
        public static Texture2D GetTexture(string fullPath)
        {
            if (instance.useTexturePool && texturePool.ContainsKey(fullPath))
            {
                return texturePool[fullPath];
            }
            return TextureUtils.LoadTexture(fullPath);
        }

        private void FullScrenn(bool b)
        {
#if !UNITY_ANDROID
            isFullScreen = b;
            if (b)
            {
                SetWindowLong(GetActiveWindow(), GWL_STYLE, WS_BORDER);
                SetWindowPos(GetActiveWindow(), HWndInsertAfter, (int)fullScreenRect.x, (int)fullScreenRect.y, (int)fullScreenRect.width, (int)fullScreenRect.height, SWP_SHOWWINDOW);
            }
            else
            {
                Screen.SetResolution(windowW, windowH, false);
            }
#endif
        }

        public static void LogToFile(object content)
        {
            Debug.Log("<color=#AAAA00>" + content + "</color>");
            string path = Application.dataPath;
            if (Application.isEditor)
            {
                path = Application.dataPath.Replace("/Assets", "");
            }
            path += "/log.txt";
            string fileContent = "";
            if (File.Exists(path))
            {
                fileContent = File.ReadAllText(path);
                fileContent += "\n" + content.ToString();
            }
            else
            {
                fileContent = content.ToString();
            }
            File.WriteAllText(path, fileContent);
        }


    }
}